import IPy
import subprocess
ips = input("请输入要检查的网段：")
try:
    i = ips.split('/')
    # 检查网段
    assert i[1] == '24' or ips[1] == '16' or ips[1] == '8'
    # 检查地址格式和获取所有IP地址存到ips中
    ips = IPy.IP(ips)
except:
    print("请输入正确的IP地址格式")
else:
    # 将得到的结果送给ips.txt
    with open("ips.txt", 'a', encoding='utf-8') as fp:
        for ip in ips:
            # 获得命令
            # ip = "ping -w 1 " + str(ip) + " &>/dev/null"
            # 将命令字符串给subprocess处理
            a = subprocess.run(f"ping -w 1 -n 1 {ip}", shell=True, stdout=subprocess.PIPE)
            # 截取IP地址输出
            # 以返回值为依据
            if a.returncode == 0:
                print(f"{ip}已被使用")
                fp.write(str(ip)+"已被使用\n")
            else:
                print(f"{ip}可以使用")
                fp.write(str(ip)+"可以使用\n")